﻿using System.Collections.Generic;
using System.Xml;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace TFSTools.TFSLibrary
{
    public sealed class TFSTeamProject : TFSServerEntity
    {
        #region Initialization

        private TeamProject serverTeamProject;
        private TFSWorkItemStore tfsWorkItemStore;

        internal TFSTeamProject(TFSConnection connection, TeamProject teamProject) : base(connection)
        {
            this.serverTeamProject = teamProject;
        }

        public TFSTeamProject(TFSConnection connection, string projectName)
            : base(connection)
        {
            this.serverTeamProject = connection.VersionControl.Service.GetTeamProject(projectName);
        }

        internal TeamProject ServerEntity { get { return this.serverTeamProject; } }

        #endregion

        #region Properties

        public string Name { get { return this.serverTeamProject.Name; } }

        public string Path { get { return "$/" + this.serverTeamProject.Name; } }

        public override string ToString() { return this.serverTeamProject.Name; }

        private TFSWorkItemStore TFSStore
        {
            get
            {
                if (this.tfsWorkItemStore == null)
                {
                    this.tfsWorkItemStore = new TFSWorkItemStore(Connection);
                }

                return this.tfsWorkItemStore;
            }
        }

        #endregion

        #region Methods

        public TFSStoredQueryDefinitionCollection GetQueryDefinitions()
        {
            this.Connection.CheckConnection();
            return TFSStoredQueryDefinitionCollection.Create(this.Connection, this);
        }

        public void GetQueries(TFSStoredQueryDefinitionCollection definitions, QueryItem queryItem)
        {
            if (queryItem is QueryFolder)
            {
                foreach (var subQueryItem in (QueryFolder)queryItem)
                {
                    this.GetQueries(definitions, subQueryItem);
                }
            }
            else if (queryItem is QueryDefinition)
            {
                definitions.Add(new TFSStoredQueryDefinition(this.Connection, (QueryDefinition)queryItem, this));
            }
        }

        #endregion
    }
}
